package khs.java_http_client.main.java;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args ) throws IOException
    {
        System.out.print("input url: ");
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        String in = bufferedReader.readLine();
        
        URL url;
        HttpURLConnection connection = null;
        
        url = new URL(in);
        connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("GET");
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        
        connection.connect();
        
        Map<String, List<String>>headerFields = connection.getHeaderFields();
        final int responseCode = connection.getResponseCode();
        final String responseMessage = connection.getResponseMessage();
        final int contentLength = connection.getContentLength();
        final String contentType = connection.getContentType();
        final URL responseURL = connection.getURL(); 
        
        System.out.println("header -> ");
        for(Map.Entry<String, List<String>>keyValue : headerFields.entrySet()){
            List<String> listValue = keyValue.getValue();
            
            System.out.println(keyValue.getKey() + ": ");
            System.out.println(listValue);
        }
        
        System.out.println("respnoseCode ->");
        System.out.println(responseCode);
        
        System.out.println("responseMessage ->");
        System.out.println(responseMessage);
        
        System.out.println("contentLength ->");
        System.out.println(contentLength);
        
        System.out.println("contentType ->");
        System.out.println(contentType);
        
        System.out.println("responseURL ->");
        System.out.println(responseURL.toString());
        
        
        final String response1 = getStreamContent(connection);
        
        
        System.out.println("");
        System.out.println("body ->");
        System.out.println(response1);
        
        connection.disconnect();
    }
    
    private static String getStreamContent(HttpURLConnection connection) throws IOException{
        InputStream inputStream = connection.getInputStream();
        
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        StringBuffer response = new StringBuffer();
        while((line = bufferedReader.readLine()) != null){
            response.append(line);
            response.append('\n');
        }
        bufferedReader.close();
       return response.toString();
    }
}
